import datetime
from apps.coffee.models import CoffeeOrder, Channel, CouponInfo, Coffee
from rest_framework.response import Response
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

from django.contrib.auth import get_user_model
from rest_framework import viewsets, mixins
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from apps.coffee_admin.serializers import EditPasswordSerializer
from apps.supply_order.utils import UntilPagination
from .serializers import ChannelSerializer, OrderSerializer, ChannelSerializers, UserSourceSerializers
from apps.coffee_admin import filters as my_filters
from .serializers import UserSerializers
from .utils import filter_channel_1, filter_channel_2, filter_channel_3


UserModel = get_user_model()


class OrderStatisticsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    首页统计
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def list(self, request, *args, **kwargs):
        username = self.request.user.username
        if username == "admin":
            chanel = None
        else:
            chanel = self.request.user.coffee_channel
        now_day = datetime.date.today()
        month_first_day = datetime.datetime(now_day.year, now_day.month, 1)
        today_order_statistics = CoffeeOrder.objects.order_statistics(chanel, now_day, filter_client=True)
        today_order_count = CoffeeOrder.objects.order_count(chanel, now_day, filter_client=True)
        month_order_statistics = CoffeeOrder.objects.order_statistics(chanel, month_first_day, filter_client=True)
        month_order_count = CoffeeOrder.objects.order_count(chanel, month_first_day, filter_client=True)
        month_payment_data = CoffeeOrder.objects.group_by_days_orders(chanel, month_first_day, filter_client=True)

        first_day = now_day.replace(day=1)
        next_month_first = first_day + datetime.timedelta(days=31)
        x_data = []
        y_data = []
        y_order_count = []
        for i in range((next_month_first - first_day).days):
            day = first_day + datetime.timedelta(days=i)
            # day = datetime.date(day.year, day.month, day.day)
            value = "0.00"
            sale_count = 0
            for k in month_payment_data:
                if k.get("day") == day:
                    value = "%.2f" % (k.get("cash") / 100)
                    sale_count = k.get("sale_count")
                    break
            x_data.append(day.strftime("%Y-%m-%d"))
            y_data.append(value)
            y_order_count.append(sale_count)

        data = {
            "today_order_statistics": today_order_statistics,
            "month_order_statistics": month_order_statistics,
            "month_order_count": month_order_count,
            "today_order_count": today_order_count,
            "y_data": y_data,
            "x_data": x_data,
            "y_order_count": y_order_count
        }
        return Response(data=data, status=200)


class SuperUserChannelViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    商户列表, super user 查看
    """
    serializer_class = ChannelSerializer
    queryset = Channel.objects.all()


class StoreViewSet(mixins.ListModelMixin, viewsets.GenericViewSet, mixins.RetrieveModelMixin):
    """
    门店列表： 通过商户看查看门店
    """
    serializer_class = ChannelSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_queryset(self):
        if self.request.user.username == "admin":
            queryset = Channel.objects.filter(channel_type=2)
        else:
            instance = self.request.user.coffee_channel
            queryset = instance.children.all()
            id_list = [i.id for i in queryset]
            id_list.append(instance.id)
            queryset = Channel.objects.filter(id__in=id_list)
        return queryset

    def retrieve(self, request, *args, **kwargs):
        pk = self.kwargs.get(self.lookup_field)
        instance = Channel.objects.filter(id=pk).first()
        if instance:
            queryset = instance.children.all()
            results = self.get_serializer(queryset, many=True).data
        else:
            return Response(status=404)
        return Response(results)


# class ClientViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,
#                     viewsets.GenericViewSet):
#     """
#     商户查看
#     """
#     serializer_class = CoffeeClientSerializer
#
#     def get_queryset(self):
#         # 只过滤自己的机器/门店
#         user_name = self.request.user.username
#         if user_name == "admin":
#             return CoffeeClient.objects.all()
#         return CoffeeClient.objects.filter(channel__key=user_name)
#

class OrdersViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.OrdersFilter
    serializer_class = OrderSerializer
    pagination_class = UntilPagination

    def get_queryset(self):
        user = self.request.user
        base_orders = CoffeeOrder.objects.all()
        if user.username == "admin":
            return base_orders
        else:
            channel = user.coffee_channel
            if channel.channel_type == 1:
                base_orders = filter_channel_1(base_orders, channel, coffee_client=True)
            elif channel.channel_type == 2:
                base_orders = filter_channel_2(base_orders, channel, coffee_client=True)
            else:
                base_orders = filter_channel_3(base_orders, channel, coffee_client=True)
            return base_orders


class UserOperationViewSet(viewsets.GenericViewSet, mixins.UpdateModelMixin):
    """
    修改密码
    """
    serializer_class = EditPasswordSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_queryset(self):
        return UserModel.objects.filter(id=self.request.user.id)


class PriceViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    """
    商品价格
    """
    queryset = []

    def list(self, request, *args, **kwargs):
        price1 = Coffee.objects.filter(c_type=1).first()
        price2 = Coffee.objects.filter(c_type=2).first()
        results = [{"price": price1.price / 100, "c_type": 1}, {"price": price2.price / 100, "c_type": 2}]
        return Response(results)


class ChannelViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin):
    """
    查看全部channel list 以及某个channel的下一级
    """
    # filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    # filter_class = my_filters.ChannelFilter
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = ChannelSerializers

    def get_queryset(self):
        user = self.request.user
        if user.username == "admin":
            return Channel.objects.filter(channel_type=1, show=True)
        else:
            instance = user.coffee_channel
            return instance.children.filter(show=True)

    def retrieve(self, request, *args, **kwargs):
        instance = Channel.objects.filter(pk=self.kwargs.get(self.lookup_field)).first()
        queryset = instance.children.filter(show=True)
        # queryset = queryset.union(Channel.objects.filter(pk=self.kwargs.get(self.lookup_field)))
        serializer = self.get_serializer(queryset, many=True)
        return Response({"data": serializer.data, "name": instance.name})


class OrderStatusViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    queryset = []

    def list(self, request, *args, **kwargs):
        orderStatus = CoffeeOrder.orderStatus
        results = []
        for i in orderStatus:
            results.append({"result": i[0], "value": i[1]})
        return Response(results)


class AddUserViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin):
    permission_classes = (IsAuthenticated, IsAdminUser,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    queryset = UserModel.objects.exclude(username="admin")
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.UsersFilter
    serializer_class = UserSerializers
    pagination_class = UntilPagination


class UserSourceViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    queryset = Channel.objects.all()
    serializer_class = UserSourceSerializers


class DiscountSourceViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    """
    优惠来源
    """
    queryset = []

    def list(self, request, *args, **kwargs):
        all_type = CouponInfo.cType
        show_c_type_list = CouponInfo.show_c_type_list
        results = []
        for i in all_type:
            key = i[0]
            if key in show_c_type_list:
                value = i[1]
                results.append({"discount_type": key, "discount_desc": value})
        results.append({"discount_type": 0, "discount_desc": "没使用券"})
        results.append({"discount_type": 10, "discount_desc": "其他"})
        return Response(results)
